<!--
 * @Author: yuanweijiang
 * @Date: 2024-01-03 14:19:33
 * @LastEditors: yuanweijiang
-->
<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<div>
				<el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList" ref="queryRef">
					<el-form-item prop="name" label="数据源名称">
						<el-input placeholder="请输入数据源名称" clearable style="max-width: 180px" v-model="state.queryForm.name" />
					</el-form-item>
					<el-form-item prop="label" label="标签">
						<el-input placeholder="请输入标签名称" clearable style="max-width: 180px" v-model="state.queryForm.label" />
					</el-form-item>
					<el-form-item prop="username" label="用户名">
						<el-input placeholder="请输入用户名" clearable style="max-width: 180px" v-model="state.queryForm.username" />
					</el-form-item>
					<el-form-item prop="dbType" label="类型">
						<el-select v-model="state.queryForm.dbType" placeholder="请选择类型">
							<el-option v-for="item in dataList" :key="item.label" :label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>
					<el-form-item prop="createTime" label="创建时间">
						<el-date-picker
							v-model="timeArr"
							type="daterange"
							value-format="YYYY-MM-DD HH:mm:ss"
							range-separator="-"
							@change="changeTime"
							start-placeholder="开始时间"
							end-placeholder="结束时间"
						>
						</el-date-picker>
					</el-form-item>
				</el-form>
				<div class="w-full flex justify-between">
					<el-form-item>
						<el-button @click="addHandle" class="ml10" icon="Plus" type="primary"> 数据源 </el-button>
					</el-form-item>
					<el-form-item>
						<el-button @click="query" class="ml10" icon="search" type="primary"> 查询 </el-button>
						<el-button icon="Refresh" @click="resetQuery">重置</el-button>
					</el-form-item>
				</div>
			</div>
			<el-table
				ref="tableRef"
				:data="state.dataList"
				:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
				row-key="path"
				style="width: 100%"
				:cell-style="tableStyle.cellStyle"
				:header-cell-style="tableStyle?.headerCellStyle"
			>
				<el-table-column prop="name" label="数据源名称" />
				<el-table-column prop="dbType" label="类型">
					<template #default="scope">
						<el-tag class="h-8" style="width: 60%" size="large">{{ scope.row.dbType.toUpperCase() }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="label" label="标签" width="230">
					<template #default="scope">
						<div class="flex gap-2 items-center justify-center">
							<el-tag size="large" v-for="item in scope.row.label?.split(',')" :key="item">{{ item }}</el-tag>
							<el-icon class="ml-2 border cursor-pointer" @click="handAddTag(scope)"><Plus /></el-icon>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="onEnable" label="连接状态">
					<template #default="scope">
						<el-switch
							v-model="scope.row.status"
							@change="switchChange(scope.row)"
							:active-value="1"
							:inactive-value="0"
							:loading="scope.row.loading"
							class="ml-2"
							style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
						/>
					</template>
				</el-table-column>
				<el-table-column prop="description" label="数据源说明" />
				<el-table-column prop="username" label="用户名" />
				<el-table-column prop="createTime" label="创建时间" show-overflow-tooltip />
				<el-table-column prop="date" label="操作">
					<template #default="scope">
						<el-button class="ml10 is-text" icon="view" type="primary" @click="editHandle(scope.row, 'detail')"> 详情 </el-button>
						<el-button class="ml10 is-text" icon="edit" type="primary" @click="editHandle(scope.row)"> 编辑 </el-button>
						<el-button class="ml10 is-text" icon="delete" type="primary" @click="deleteHandle(scope.row)"> 删除 </el-button>
					</template>
				</el-table-column>
			</el-table>
			<Pagination v-bind="state.pagination" @current-change="currentChangeHandle" @size-change="sizeChangeHandle"> </Pagination>
		</div>
		<addProject ref="addPro" @refresh="getDataList" />
		<addTag ref="addTagRef" @refresh="uplateTag" />
	</div>
</template>

<script lang="ts" name="proJect" setup>
import { getList, addOrUpdateDataSource, testConnection, updateStatus, removeId } from '/@/api/datasource';
import { BasicTableProps, useTable } from '/@/hooks/table';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { useI18n } from 'vue-i18n';
import addTag from './components/addTag.vue';
import addProject from './components/dataDialog.vue';
import roleId from './components/project/roleid.vue';
import { useUserInfo } from '/@/stores/userInfo';
import { useDict } from '/@/hooks/dict';

// 引入组件
const { t } = useI18n();
// 定义变量内容
const tableRef = ref();
const queryRef = ref();
const roleDetail = ref();
const addTagRef = ref('');
const addPro = ref('');
const projectDio = ref('');
const timeArr = ref([]);
const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {},
	pageList: getList,
	props: {
		item: 'records',
		totalCount: 'total',
	},
});
const { dataList } = useDict('dataList');
//查看文件列表
function lookDetail(name: string, proName: any) {
	projectDio.value.state.queryForm.projectName = proName.wokeSpaceName;
	projectDio.value.title = name;
	projectDio.value.openDialog();
	projectDio.value.state.queryForm.projectName = proName.wokeSpaceName;
	projectDio.value.state.dataList = [];
	if (name === '文件') {
		projectDio.value.state.pageList = fileDataSourceLsit;
	} else {
		projectDio.value.state.pageList = geoLayerList;
		projectDio.value.state.pagination = {};
	}
}
//新建项目
const addHandle = () => {
	addPro.value.openDialog({});
};
function changeTime(time) {
	state.queryForm.startTime = time[0];
	state.queryForm.endTime = time[1];
}
const editHandle = (row, title) => {
	if (title === 'detail') {
		addPro.value.openDialog({ queryForm: row, flag: false });
		return;
	}
	addPro.value.openDialog({ queryForm: row });
};
//新建标签
function handAddTag(scope) {
	if (scope.row.label) {
		addTagRef.value.openDialog({ tagList: scope.row.label.split(','), id: scope.row.id });
	} else {
		addTagRef.value.openDialog({ id: scope.row.id });
	}
}
const { getDataList, tableStyle, currentChangeHandle, sizeChangeHandle } = useTable(state);
async function uplateTag(tagArr) {
	let newObj = state.dataList.filter((item) => {
		return item.id == tagArr.id;
	});
	newObj[0].label = tagArr.tagList.join(',');
	try {
		await addOrUpdateDataSource(newObj[0]);
		useMessage().success('标签修改成功');
		getDataList();
	} catch (error) {}
}
async function switchChange(item) {
	item.loading = true;
	if (item.status == 1) {
		try {
			await testConnection({ id: item.id });
		} catch (error) {
			useMessage().error('数据源连接测试失败');
			item.status = 0;
			item.loading = false;
			return;
		}
	}
	try {
		await updateStatus({ id: item.id, status: item.status });
		useMessage().success(item.status == 1 ? '已连接' : '已断开');
		getDataList();
	} catch (error) {
		useMessage().error('连接失败');
	}
	item.loading = false;
}
async function deleteHandle(data) {
	try {
		await useMessageBox().confirm(t('common.delConfirmText'));
	} catch {
		return;
	}
	try {
		await removeId({ id: data.id });
		useMessage().success('删除成功');
		getDataList();
	} catch (error) {}
}
// 搜索事件
const query = () => {
	state.dataList = [];
	getDataList();
};

// 清空搜索条件
const resetQuery = () => {
	state.queryForm = {};
	timeArr.value = [];
	getDataList();
};

// 删除操作
const handleDelete = async (row: any) => {
	try {
		await useMessageBox().confirm(t('common.delConfirmText'));
	} catch {
		return;
	}

	try {
		await delPost({ wokeSpaceName: row.wokeSpaceName });
		// 更新上下文的 user信息
		useUserInfo().setUserInfos();
		getDataList();
		useMessage().success(t('common.delSuccessText'));
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};
//修改操作
const handleEdit = (row: any) => {
	addPro.value.form = { ...row };
	addPro.value.title = '修改项目';
	addPro.value.openDialog();
	addPro.value.oldWokeSpaceName = row.wokeSpaceName;
};
//查看权限
const lookRole = (row: any) => {
	roleDetail.value.openDialog();
	roleDetail.value.wokeSpaceName = row.wokeSpaceName;
	roleDetail.value.getInfo(row.wokeSpaceName);
};
</script>
